<?php

namespace App\Library\Pay;

use App\Events\PayNotifyEvent;
use App\Modules\Apicrzs\Services\Notify\WxNotifyServices;
use EasyWeChat\Pay\Application as payApp;
use EasyWeChat\Pay\Message;
use Illuminate\Support\Facades\Log;

class V3WechatPay
{

    const API_JSAPI_URL = 'v3/pay/transactions/jsapi';

    protected static $instance;
    /**
     * 实例化
     * @param array alipay
     * @return static
     */
    public static function instance(array $alipay = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($alipay);
        }
        return self::$instance;
    }

    /**
     * 创建订单返回支付参数
     * @param $pay_params
     * @return array|mixed[]
     */
    public static function payPostJson($pay_params)
    {
        $wechat_config = getWxConfig('MiniApp');
        $pay_params['appid'] =  $wechat_config['app_id'];
        $pay_params['mchid'] =  $wechat_config['mch_id'];
        // 创建微信支付对象
        $wechat = new payApp($wechat_config);
        // 第一步：JSAPI 下单，组装请求参数

        $response = $wechat->getClient()->postJson("v3/pay/transactions/jsapi",$pay_params);
        $result = $response->toArray(false);
        // 请求失败
        if (!isset($result['prepay_id'])) {
            return ['code' => 0, 'data' => '', 'msg' => $result['message']];
        }
        // 第二步：组装小程序调起支付 API
        $prepayId = $result['prepay_id'];
        $appId = $wechat_config['app_id'];
        // 默认RSA，v2要传MD5
        $config = $wechat->getUtils()->buildMiniAppConfig($prepayId, $appId,  'RSA');
        return $config;
    }



    /**
     * 微信支付 回调 V3
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \ReflectionException
     * @throws \Throwable
     */
    public static function handleNotify(){
        $wechat = new payApp(getWxConfig('MiniApp'));
        $server = $wechat->getServer();
        $server->handlePaid(function (Message $message,\Closure $next) {
            $out_trade_no = $message['out_trade_no'];
            $transaction_id = $message['transaction_id'];
            $content='39- 微信支付订单号:'.$message['transaction_id'].',商户订单号:'.$message['out_trade_no'].',支付者:'.$message['payer']['openid'].'状态：'.$message['trade_state'];
            xdebug($content,'微信支付-回调-api','pay/notify/v3wechat');
            xdebug($message,'微信支付-回调-原始数据','pay/notify/v3wechat');
            $data = [
                'attach' => $message['attach'],
                'out_trade_no' => $out_trade_no,
                'transaction_id' => $transaction_id
            ];
        });
        return $server->serve();

    }

}
